<template>
  <!-- <h4>新增任务</h4> -->
  <el-dialog :title="mode=='add'?'编辑':'查看'"
             class="addTask"
             width='500px'
             :close-on-click-modal="false"
             :visible.sync="visible">
    <!-- 具体表单 -->
    <el-form :model="dataForm"
             :rules="dataRule"
             label-position="left"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmit()">
      <el-form-item label="任务名称"
                    prop="taskName">
        <el-input v-model="dataForm.taskName"
                  placeholder="任务名称"></el-input>
      </el-form-item>
      <el-form-item label="任务编号"
                    prop="taskNo">
        <el-input v-model="dataForm.taskNo"
                  :disabled="true"
                  placeholder="任务编号"></el-input>
      </el-form-item>
    </el-form>
    <div class="box">
      <div class="excel">
        <el-upload v-if="mode == 'add'"
                   class="upload-demo"
                   :action="action"
                   :before-upload="beforeAvatarUpload"
                   :on-success="handleAvatarSuccess"
                   :headers='headers'
                   :show-file-list='false'
                   multiple
                   :data='updatas'
                   :limit="1"
                   :file-list="fileList">
          <el-button type="primary">Excel导入</el-button>
        </el-upload>
        <el-button type="primary"
                   @click="exportExcel()">Excel导出</el-button>
      </div>
      <div class="box_list">
        <div class="title">
          <span>姓名</span>
          <span>电话</span>
        </div>
        <div class="addList"
             v-for="(item,index) in nameList"
             :key='index'>
          <!-- <el-input v-model="input"></el-input>
          <el-input v-model="input"></el-input> -->
          <div class="itemInput">{{item.userName}}</div>
          <div class="itemInput">{{item.moblie}}</div>
          <i class='el-icon-close'
             v-if="mode == 'add'"
             @click="delet(item.uuid)"></i>
          <span v-if="item.isAccept==1">领取</span>
        </div>
        <!-- 新增内容 -->
        <div class="addList"
             v-if="addListVisble">
          <div class="itemInput">
            <input type="text"
                   v-model="addList.userName">
          </div>
          <div class="itemInput">
            <input type="text"
                   v-model="addList.moblie">
          </div>
          <i class='el-icon-close'
             v-if="mode == 'add'"
             @click="delet"></i>
        </div>
      </div>
      <!-- 新增按钮 -->
      <div class="addBtn"
           v-if='mode=="add"'>
        <el-button type="primary"
                   @click="addBtn"
                   icon="el-icon-plus"
                   circle></el-button>
      </div>
    </div>
    <span slot="footer"
          class="dialog-footer">
      <el-button type="primary"
                 class="btn"
                 @click="addSave"
                 v-if="mode == 'add'">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      // 判断添加还是编辑
      mode: 'add',
      workerIdVisb: true,
      // 隐藏
      visible: false,
      // 数据
      dataForm: {
        taskName: '',
        taskNo: ''
      },
      // 名单
      nameList: {},
      // 新增
      addList: {
        userName: '',
        moblie: ''
      },
      // 头
      headers: {
        token: ''
      },
      // 上传相关
      fileList: [],
      action: '',
      addListVisble: false,
      updatas: {
        taskNo: ''
      },
      // 验证
      dataRule: {
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              // 手机号码正则校验
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
              if (_reg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的手机号码'))
              }
            }
          }
        ]
      }
    }
  },
  created () {
    // 上传地址
    this.action = this.$baseUrl + '/task/name-list/import'
    this.headers.token = this.$cookie.get('token')
    // if (sessionStorage.getItem('userRoleId') === '2') {
    //   this.workerIdVisb = false
    // }
  },
  activated () {
    // this.update.taskNo = this.dataForm.taskNo
    // console.log(this.update.taskNo)
  },
  methods: {
    // 父调用的方法，新增
    addInit () {
      this.visible = true
    },
    // 父调用的方法，查询
    init (taskNo, taskName) {
      this.dataForm.taskName = taskName
      this.dataForm.taskNo = taskNo
      this.updatas.taskNo = this.dataForm.taskNo
      this.visible = true
      this.getList()
    },
    async getList () {
      await this.$http({
        url: this.$http.adornUrl('/task/name-list/list?taskNo=' + this.dataForm.taskNo),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.nameList = data.list
      })
    },
    // 修改提交
    update () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl('/sys/task/update'),
            method: 'post',
            data: this.$http.adornParams(this.dataForm)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  // 成功之后的回调
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 新增
    // /sys/tax/save
    addSave () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.addListVisble = false
          if (this.addList.userName && this.addList.moblie) {
            this.nameList.push(this.addList)
          }
          this.addList = {
            userName: '',
            moblie: ''
          }
          let TaskNameListVO = {}
          TaskNameListVO.taskName = this.dataForm.taskName
          TaskNameListVO.taskNo = this.dataForm.taskNo
          TaskNameListVO.list = this.nameList
          this.$http({
            url: this.$http.adornUrl('/task/name-list/save'),
            method: 'post',
            data: this.$http.adornParams(TaskNameListVO)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  // 成功之后的回调
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    // 删除
    async delet (id) {
      console.log(id)
      if (id instanceof Object) {
        this.$message.error('未保存的不支持删除，请先保存')
      } else {
        let uuids = [id]
        await this.$http({
          url: this.$http.adornUrl('/task/name-list/delete'),
          method: 'post',
          data: this.$http.adornParams(uuids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(data.msg)
          }
        })
      }
    },
    addBtn () {
      this.addListVisble = !this.addListVisble
      if (this.addList.userName && this.addList.moblie) {
        this.nameList.push(this.addList)
      }
      this.addList = {
        userName: '',
        moblie: ''
      }
    },
    // 上传前
    beforeAvatarUpload (f) {
      if (!(f.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || f.type === 'application/vnd.ms-excel')) {
        this.$message.error('上传文件只能是 xls和xlsx 格式!')
        return false
      } else {
        return true
      }
    },
    // 导入成功处理函数
    handleAvatarSuccess (res, file) {
      if (res.code === 0) {
        this.$message.success(res.msg)
        this.getList()
      } else {
        this.$message.error(res.msg)
      }
      this.fileList = []
    },
    // 导出函数--等接口和接口参数,怪怪的。。
    exportExcel () {
      this.$http({
        url: this.$http.adornUrl('/task/name-list/exmport?taskNo=' + this.dataForm.taskNo),
        method: 'post',
        responseType: 'blob'
        // data: this.$http.adornParams({
        //   taskNo: this.dataForm.taskNo
        // })
      }).then((_res) => {
        let blob = new Blob([_res.data], {
          type: 'application/vnd.ms-excel'
        })
        let url = window.URL.createObjectURL(blob)
        let a = document.createElement('a')
        a.href = url
        // document.body.appendChild(a)
        // window.open()
        a.download = '内置任务名单.xlsx'
        a.click()
        window.URL.revokeObjectURL(a.href)
      })
    }
    // 结束
  }
}
</script>

<style lang="scss">
.addTask {
  // text-align: center;
  .el-input.el-input--medium {
    width: 370px;
  }
  .el-dialog__header {
    background-color: #f8f8f8;
  }
  .el-dialog__body {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
  .btn {
    width: 370px;
  }
  .dialog-footer {
    text-align: center !important;
    padding-bottom: 39px;
  }
  .el-dialog__footer {
    text-align: center;
    padding-bottom: 39px;
  }
  .box {
    & > div {
      margin-bottom: 10px;
    }
    .excel {
      display: flex;
      justify-content: space-between;
    }
    .center,
    .addList {
      i {
        cursor: pointer;
        &:hover {
          color: #4876e7;
        }
      }
    }
    .title {
      width: 100%;
      display: flex;
      span {
        line-height: 2;
        padding: 0 10px;
      }
      span:first-child {
        width: 162px;
        border-right: 1px solid #606266;
      }
    }
    // .center {
    //   width: 100%;
    //   display: flex;
    //   & > span:first-child {
    //     width: 162px;
    //   }
    //   & > span:nth-child(2) {
    //     width: 162px;
    //     margin-right: 14px;
    //   }
    // }
    .addList {
      border-top: 1px solid #606266;
      overflow: hidden;
      i {
        margin: 7px 28px 7px 0;
      }
      span {
        line-height: 26px;
      }
      .itemInput {
        display: inline-block;
        padding: 5px 0;
        width: 162px;
        padding-left: 10px;
        height: 28px;
        float: left;
        input {
          width: 100%;
          border: none;
          box-sizing: border-box;
          height: 18px;
          padding: 0;
          font-size: 14px;
        }
        &:first-of-type {
          border-right: 1px solid #606266;
        }
      }

      & > input:nth-child(2) {
        margin-right: 10px;
        padding-right: 0;
      }
    }
    .addBtn {
      text-align: center;
    }
  }
  .box_list {
    border: 1px solid #606266;
    border-radius: 1px;
  }
}
</style>
